<?php

/**
 * 节点管理
 */
namespace app\topics\model;

use app\system\model\SystemModel;

class TopicsNodeModel extends SystemModel {

    protected $infoModel = [
        'pri' => 'node_id',
        'validate' => [
            'name' => [
                'len' => ['1, 50', '名称只能为1~50个字符', 'must', 'all'],
            ],
            'description' => [
                'len' => ['1, 250', '描述只能为1~250个字符', 'must', 'all'],
            ],
        ],
        'format' => [
            'name' => [
                'function' => ['htmlspecialchars', 'all'],
            ],
            'description' => [
                'function' => ['htmlspecialchars', 'all'],
            ],
            'sort' => [
                'function' => ['intval', 'all'],
            ],
            'post_role' => [
                'callback' => ['formatImplode', 'all']
            ],
            'moderator' => [
                'callback' => ['formatImplode', 'all']
            ]
        ],
        'into' => '',
        'out' => '',
    ];

    protected function formatImplode($field, $data) {
        return $data ? implode(',', $data) : '';
    }

    protected function base($where) {
        $list = $this->table('topics_node(A)')
            ->join('topics_node_group(B)', ['B.group_id', 'A.group_id'])
            ->field(['A.*', 'B.name(group_name)'])
            ->where((array)$where);
        return $list;
    }

    public function loadList($where = array(), $limit = 0, $order = '') {
        $list = $this->base($where)
            ->limit($limit)
            ->order($order)
            ->select();
        $typeList = target('topics/Topics', 'service')->getTypeAll();
        foreach ($list as $key => $vo) {
            $list[$key]['url'] = url($typeList[$vo['type']]['list_url'], ['id' => $vo['node_id']]);
        }
        return $list;
    }

    public function countList($where = array()) {
        return $this->base($where)->count();
    }

    public function getWhereInfo($where) {
        return $this->base($where)->find();
    }

    public function nodeList($where = []) {
        $groupList = target('topics/TopicsNodeGroup')->loadList([], 0, 'sort asc, group_id asc');
        $nodeList = $this->loadList($where, 0, 'A.sort asc, A.node_id asc');

        $data = [];
        foreach ($groupList as $key => $vo) {
            $data[$vo['group_id']] = $vo;
        }
        foreach ($nodeList as  $vo) {
            $data[$vo['group_id']]['node'][] = $vo;
        }
        return $data;
    }


}